package com.tcs.check.net;

import java.io.IOException;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.tcs.model.ipdata.IpDataBean;
import com.tcs.model.porxypool.proxyPoolBean;
import com.tcs.util.constant.SystemConstants;
import com.tcs.util.staticpack.StaticPack;

/**
* @Title: NetChecked.java
* @Package com.tcs.check.net
* @author 神经刀
* @date 2018年8月10日
* @version V1.0
 */
@Component(value="netChecked")
public class NetChecked implements INetChecked {
	
	private final Logger logger = LoggerFactory.getLogger(NetChecked.class);

	@Resource(name="staticPack")
	private StaticPack<String, proxyPoolBean> staticPack;
	
	/**
	 * 判断ip和端口是否有效
	 */
	@Override
	public boolean checkThrough(IpDataBean ipDataBean) {
		proxyPoolBean proxyPoolBean = null;
		if (staticPack.containsKey(SystemConstants.ProxyPool.PROXYPOOLMODEL)) {
			proxyPoolBean = staticPack.get(SystemConstants.ProxyPool.PROXYPOOLMODEL);
		} else {
			throw new NullPointerException(SystemConstants.ProxyPool.PROXYPOOLMODEL + "is null!");
		}
		if (null == ipDataBean) throw new NullPointerException(" ipDataBean对象为null,无法验证!.");
		if (null == proxyPoolBean || null == proxyPoolBean.getNetConfig() || StringUtils.isEmpty(proxyPoolBean.getNetConfig().getAddress())) throw new NullPointerException(" 参数异常,无法验证.");
		try {
			Jsoup.connect(proxyPoolBean.getNetConfig().getAddress())
			.proxy(ipDataBean.getIp(),ipDataBean.getPort())
			.timeout(2 * 1000)
			.get();
			return true;
		} catch (IOException e) {
			logger.error("判断ip和端口是否有效! ipDataBean : " + ipDataBean.toString() , e);
		}
		return false;
	}

}